from django.db.models import Q, F
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from django.views import View
from django.db import DatabaseError
import json

from student.models import StudentInfo
from course.models import ClassInfo
from sc.models import SCInfo

class index(View):
    """获取信息"""
    def get(self, request):
        # 查询所有学生和课程
        # ClassInfo.objects.filter(Cno=1).update(Ccredit=6)
        # ClassInfo.objects.filter(Cno=2).update(Ccredit=2)
        # ClassInfo.objects.filter(Cno=3).update(Ccredit=3)
        # ClassInfo.objects.filter(Cno=4).update(Ccredit=2)

        try:
            course_list = list(ClassInfo.objects.all().order_by('Cno').values())
        except DatabaseError:
            return JsonResponse({'code': 0, 'msg': '操作失败'})
        # 返回数据
        return JsonResponse({'code': 200, 'msg': '数据提取完成', "data": course_list})


class selectCourse(View):
    """ 选课操作 """
    def get(self, request):
        return HttpResponse("this is the select-course page！")

    def post(self, request):
        # 获取参数
        Sno = str(request.POST.get('Sno'))
        course_list = request.POST.get('course_list')
        # 将字符串转成json格式
        course_list = json.loads(course_list)


        # 检查选课表中是否有重复选课的情况
        try:
            for i in course_list:
                if SCInfo.objects.filter(Q(Cno=i['Cno']) & Q(Sno=Sno)).count() >= 1:
                    return JsonResponse({'code': 1, 'msg': '请勿重复选相同的课'})
        except DatabaseError:
            return JsonResponse({'code': 0, 'msg': '出错了'})

        # 选课表中插入数据
        try:
            for i in course_list:
                C = ClassInfo.objects.get(pk=i['Cno'])  # 先查课程表的主键
                S = StudentInfo.objects.get(pk=Sno)  # 查学生表的主键
                SCInfo.objects.create(Cno=C, Sno=S)  # 外键字段用主表对应的Model类对象赋值
                # 修改可选课程数目
                Ccredit = ClassInfo.objects.filter(Cno=i['Cno']).values('Ccredit')
                ClassInfo.objects.filter(Cno=i['Cno']).update(Ccredit=Ccredit[0]['Ccredit']-1)

        except DatabaseError:
            return JsonResponse({'code': 0, 'msg': '选课失败'})

        # 返回结果
        return JsonResponse({'code': 200, 'msg': '选课成功'})


class reset(View):
    """退课"""
    def get(self, request):
        return HttpResponse("this is the reset page")

    def post(self, requset):
        # 接收参数
        Sno = requset.POST.get('Sno')
        # 查询数据,删除记录
        try:
            data = list(SCInfo.objects.filter(Sno=Sno).values())
            for i in data:
                # 退课以后课程容量加1
                ClassInfo.objects.filter(Cno=i['Cno_id']).update(Ccredit=F('Ccredit')+1)
                # 删除记录
                SCInfo.objects.filter(Sno=Sno).first().delete()

        except DatabaseError:
            return JsonResponse({'code': 0, 'msg': '重置失败'})

        # 返回结果
        return JsonResponse({'code': 200, 'msg': 'OK'})
